package ink.ykb.demo.config;

import java.net.UnknownHostException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;

@Configuration
public class RedisConfig {
  
  @Bean("redisTemplate")
  public RedisTemplate<Object,Object> getRedisTemplate(RedisConnectionFactory connectionFactory,ObjectMapper objectMapper) throws UnknownHostException{
      
      RedisTemplate<Object,Object> template = new RedisTemplate<Object,Object>();
      StringRedisSerializer stringSerializer = new StringRedisSerializer();
      Jackson2JsonRedisSerializer<Object> jsonSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
      jsonSerializer.setObjectMapper(objectMapper);
      template.setConnectionFactory(connectionFactory);
      template.setDefaultSerializer(jsonSerializer);
      template.setKeySerializer(stringSerializer);
      template.setValueSerializer(jsonSerializer);
      template.setHashKeySerializer(stringSerializer);
      template.setHashValueSerializer(jsonSerializer);
      
      return template;
  }
  
  @Bean
  public RedisTemplate<String,Object> getStringRedisTemplate(RedisConnectionFactory connectionFactory,ObjectMapper objectMapper) throws UnknownHostException{
      
      RedisTemplate<String,Object> template = new RedisTemplate<String,Object>();
      StringRedisSerializer stringSerializer = new StringRedisSerializer();
      Jackson2JsonRedisSerializer<Object> jsonSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
      jsonSerializer.setObjectMapper(objectMapper);
      template.setConnectionFactory(connectionFactory);
      template.setDefaultSerializer(jsonSerializer);
      template.setKeySerializer(stringSerializer);
      template.setValueSerializer(jsonSerializer);
      template.setHashKeySerializer(stringSerializer);
      template.setHashValueSerializer(jsonSerializer);
      
      return template;
  }
  

}
